"""
智能测算系统主程序
"""
import logging
from typing import Dict, Any
import argparse

from engine import CalculationEngine, EvaluationEngine
from data.exporters import ExcelExporter, ReportExporter

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


def run_calculation(config: Dict[str, Any]) -> Dict[str, Any]:
    """
    执行计算任务
    
    Args:
        config: 计算配置
        
    Returns:
        计算结果
    """
    try:
        # 初始化计算引擎
        engine = CalculationEngine(config)
        
        # 执行计算
        result = engine.execute(config["input_data"])
        
        # 导出结果
        if "export" in config and config["export"]:
            exporter = ExcelExporter()
            filepath = exporter.export_calculation_results(result)
            logger.info(f"计算结果已导出到: {filepath}")
            
        return result
    except Exception as e:
        logger.error(f"计算执行失败: {str(e)}", exc_info=True)
        raise


def run_evaluation(config: Dict[str, Any]) -> Dict[str, Any]:
    """
    执行结果评价
    
    Args:
        config: 评价配置
        
    Returns:
        评价结果
    """
    try:
        # 初始化评价引擎
        engine = EvaluationEngine(config)
        
        # 执行评价
        result = engine.execute(config["input_data"])
        
        # 导出报告
        if "export" in config and config["export"]:
            exporter = ReportExporter()
            filepath = exporter.export_evaluation_report(
                result["evaluation_result"],
                config["input_data"]["scene_info"],
                format="pdf"
            )
            logger.info(f"评价报告已导出到: {filepath}")
            
        return result
    except Exception as e:
        logger.error(f"评价执行失败: {str(e)}", exc_info=True)
        raise


def main():
    """
    主函数
    """
    # 解析命令行参数
    parser = argparse.ArgumentParser(description='智能测算系统')
    parser.add_argument('--config', type=str, required=True, help='配置文件路径')
    parser.add_argument('--mode', type=str, choices=['calculate', 'evaluate'], required=True, help='运行模式')
    args = parser.parse_args()
    
    try:
        # 加载配置
        import json
        with open(args.config, 'r', encoding='utf-8') as f:
            config = json.load(f)
        
        # 根据模式执行
        if args.mode == "calculate":
            result = run_calculation(config)
        else:
            result = run_evaluation(config)
        
        # 输出结果
        print("执行完成，结果:")
        print(json.dumps(result, indent=2, ensure_ascii=False))
        
    except Exception as e:
        logger.error(f"主程序执行失败: {str(e)}", exc_info=True)
        raise


if __name__ == "__main__":
    main()